package cn.schoolwow.quickdao.module.database.dml.json.service.delete;

import cn.schoolwow.quickdao.module.database.dml.common.domain.GetBatchParametersSupplier;
import cn.schoolwow.quickdao.module.database.dml.common.domain.ManipulationOption;
import cn.schoolwow.quickdao.module.database.dml.json.flow.common.DeleteBySingleUniqueFieldFlow;
import cn.schoolwow.quickdao.module.database.dml.json.flow.common.SetDeleteJSONObjectParameterFlow;
import cn.schoolwow.quickdao.module.database.dml.json.flow.common.SetDeleteJSONObjectStatementFlow;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteBatchUpdateConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

public class DeleteJSONArrayFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        ManipulationOption manipulationOption = flowContext.checkInstanceData(ManipulationOption.class);
        if(manipulationOption.uniqueFieldNames.size()==1){
            flowContext.executeFlowList(new DeleteBySingleUniqueFieldFlow());
        }else{
            JSONArray instances = flowContext.checkData("instances", JSONArray.class);
            flowContext.startFlow(new SetDeleteJSONObjectStatementFlow())
                    .next(new ExecuteBatchUpdateConnectionFlow())
                    .putTemporaryData("perBatchCount", manipulationOption.perBatchCount)
                    .putTemporaryData("name", "批处理删除JSONArray")
                    .putTemporaryData("size", instances.size())
                    .putTemporaryData("getBatchParametersSupplier",new GetBatchParametersSupplier() {
                        @Override
                        public List<Object> getBatchParameters(Integer index) throws Exception {
                            JSONObject instance = instances.getJSONObject(index);
                            flowContext.putTemporaryData("instance", instance);
                            flowContext.executeFlowList(new SetDeleteJSONObjectParameterFlow());
                            List<Object> parameters = (List<Object>) flowContext.checkData("parameters");
                            return parameters;
                        }
                    })
                    .execute();
        }
    }

    @Override
    public String name() {
        return "删除JSONArray";
    }

}
